<?php

namespace app\services;

use SimpleSoftwareIO\QrCode\Facades\QrCode;
use EasyWeChat\Factory;
use plugin\admin\app\model\User;
use SimpleSoftwareIO\QrCode\Generator;

class QrcodeService
{
    public static function generate($id, $type = 'article')
    {
        $config = ConfigService::getByGroup('wechat');
        $app = Factory::miniProgram([
            'app_id' => $config['wechat_app_id'],
            'secret' => $config['wechat_app_secret'],
            'response_type' => 'array'
        ]);

        $url = '';

        switch ($type) {
            case 'article':
                $url = '/pages/public/notice/system';
                break;
            case 'goods':
                $url = '/pages/goods/good_dateils';
                break;
            case 'prize_draw':
                $url = '/pages_draw/draw/details';
                break;
            case 'register':
                $url = '/pages/login/register';
                break;
        }

        $user = User::where('id', get_user_id())->first();

        $response = $app->app_code->get($url . '?invite_code=' . $user['invite_code'] . '&id=' . $id, [
            'env_version' => ConfigService::get('wechat_mini_program_code_version')
        ]);

        $sign = md5($id . get_user_id() . $type);

        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->saveAs(public_path() . '/mini_program_qrcode', $sign  . '.png');
            $inviteQrcodeUrl = full_url('/mini_program_qrcode/' . $sign . '.png');

            return $inviteQrcodeUrl;
        }

        throw new \Exception('生成二维码失败');
    }

    public static function generateQrcode()
    {
        try {
            // 要生成二维码的内容
            $content = 'https://example.com';

            $relativePath = '/qrcodes/' . get_user_id() . '_invite_code.png';
            if (!file_exists(public_path() . $relativePath)) {
                (new Generator())->format('png')
                    ->margin(1)
                    ->generate($content, public_path() . $relativePath);
            }

            return full_url($relativePath);

        } catch (\Exception $e) {
            throw new \Exception('生成二维码失败: ' . $e->getMessage());
        }
    }
}